package dp.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class SpringUtil  implements ApplicationContextAware{

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }
    
    public static String[] getBeanNamesForType(Class<?> arg0){
    	return applicationContext.getBeanNamesForType(arg0);
    }
    
    public static <T> T getBean(Class<T> clazz){
    	return applicationContext.getBean(clazz);
    }
    
    /**
     * 取HttpRequest
     * @return request
     */
    public static HttpServletRequest getRequest(){
    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 
    	return request;
    }
    
    /**
     * 取HttpServletResponse
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse(){
    	HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    	return response;
    }
    
    /**
     * 取ServletContext
     * @return
     */
    public static ServletContext getServletContext(){
    	return ContextLoader.getCurrentWebApplicationContext().getServletContext();
    }
}